package fa7.socialcode.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import fa7.socialcode.dao.ExampleDao;
import fa7.socialcode.model.Example;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve Example objects.
 *
 * @author Matt Raible
 */

//um apelido pro example
@Repository(value = "exampleDao")
public class ExampleDaoHibernate implements ExampleDao {
    HibernateTemplate hibernateTemplate;
    //Somente para log
    Log logger = LogFactory.getLog(ExampleDaoHibernate.class);
    
    @Autowired
    public ExampleDaoHibernate(SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    public List getExamples() {
        return hibernateTemplate.find("from Example");
    }

    public Example getExample(Long id) {
        Example example = (Example) hibernateTemplate.get(Example.class, id);
        if (example == null) {
            throw new ObjectRetrievalFailureException(Example.class, id);
        }
        return example;
    }

    public void saveExample(Example example) {
        hibernateTemplate.saveOrUpdate(example);

        if (logger.isDebugEnabled()) {
            logger.debug("exampleId set to: " + example.getId());
        }
    }

    public void removeExample(Long id) {
        hibernateTemplate.delete(getExample(id));
    }

    public void removeExample(Example ex) {
      hibernateTemplate.delete(getExample(ex.getId()));
  }

}
